<?php

namespace Jxgl\Controller;
use Think\Page;
use Think\Controller;


/**
 * 读书节管理控制器
 * @author水月居 <singliang@163.com>
 */
class DushujieController extends Controller {
    function _initialize()
    {
        header("Content-Type:text/html;charset=utf-8"); 

        if (!is_login()) {
            $this->error('本模块必须登录后才能使用。',U('/Ucenter/Member/login'),2);
        }
        $this->rootPath = './Uploads/Dushujie/';
        $this->classlist=M('StudentClass')->field('id,bj_name,headteacher')->select();

        $this->dushujieModel=D('Jxgl/JxglDushujie');

        $catTitle=modC('PAPER_CATEGORY_TITLE','读书节管理','Dushujie');        

        $sub_menu['left'][]= array('tab' => 'home', 'title' => '读书节管理', 'href' =>  U('index'));
        $this->assign('sub_menu', $sub_menu);
        $this->assign('current','home');

    }

    /**
     * 读书节管理首页
    */
    public function index(){
    	$this->redirect('/Jxgl/Dushujie/viewDushujie');
	    $this->display();
    }


 public function upDushujie(){
 
        $dushujie=D('JxDushujie');
	    $order=array('update_time'=>'desc');
		$map['year']=Date('Y'); 
	    $dushulist=$this->dushujieModel->where($map)->order($order)->limit('0,5')->select();
		$this->assign('list', $dushulist);
		if(IS_POST){
			$data=I('post.');			
            if(!$data['title']){
                $this->error("请填写节目名称再上报");
            }
            if(!$data['teacher']){
                $this->error("请填写班主任姓名");
            }else{
            	$data['headteacher']=$data['teacher'];
            }
			 if(!$data['class']){
                $this->error("请先选择班级再上报");
            }else{
              $data['grade']=M('StudentClass')->where(array('bj_name'=>$data['class']))->getField('grade');	
            }
			$data['year']=Date('Y');			
			$data['sort']=1;
			$data['abstract']=str_DeleteHtml($data['abstract']);
			           
         $data=$this->dushujieModel->create($data);
        
		         if($this->dushujieModel->add($data)){
		         	$this->success('节目上报成功！');
		         }else{
		         	$this->error($this->dushujieModel->getError());

		         }
         	
				             
			
			}
 
           $this->display();
	}
  //浏览读书节节目      
  public function viewDushujie(){
      
  	  $map['year']=I('year',date('Y'));
  	    $dushujieModel=$this->dushujieModel;
	    $order=array('grade'=>'asc','class'=>'asc');
	    $list=$dushujieModel->order($order)->where($map)->select();
  		$this->assign('list', $list); 
      $this->assign('ayear', $map['year'] );
      $this->display();
	}



	/*下载音乐文件*/
  public function downloadmusic($id=0){
  	  $File = $this->dushujieModel;
      $info=$File ->field('id,url,filename,class,title')->find(I('get.id'));
		$info['type'] = "audio/mpeg";
		if(empty($info)){
			$this->error = "不存在的文档ID：{$id}";
			return false;
		}
		$info['rootpath'] = $this->rootPath;
		//$url=$info['rootpath'].$info['url'];
		//dump($info);	
		//$b=is_file($fileurl);	

		if(false === $File->downLocalFile($info)){
			$this->error = $File->getError();
		}
	}


  public function editDushujie(){
     
      // dump($this->dushujieModel);
      $this->my = $this->dushujieModel ->find(I('get.id'));


        $this->display();
    }
  public function doEditjiemu(){
      if(IS_POST){           
          // //保存表单数据
           $data= I("post.");
           $data=$this->dushujieModel->create($data);            
           $result = $this->dushujieModel->save($data);          
               if($result !== false){               
                    $this->success('更新成功', Cookie('__forward__'));                 
                    }else{
                    echo '数据更新失败！';
                    $this->error($dushujie->getError());
                    }          
            }    
    }

  //节目排序
	public function sortDushujie(){
      $map['year']=I('year',date('Y'));
      $dushujie=$this->dushujieModel;
      $order=array('class'=>'asc','sort'=>'desc');
      $list=$dushujie->order($order)->where($map)->select();
      $this->assign('list', $list); 
      $this->assign('ayear', $map['year'] ); 
	    $this->display();
		}
    public function exportDushujie($year=''){
      $year=I('year',date('Y'));
      $map['year']=$year;
      $map['status']=1;
      $Model=$this->dushujieModel;
      $order=array('grade'=>'asc','class'=>'asc');
      //学生数据查询
      //    ["id"] => string(2) "54"

       $list=$Model
       ->field('class,headteacher,title,xingshi,abstract,show_time,sort')->order($order)
       ->where($map)->select();
       // dump($list);die;
       $width=array('4','8','12','12','8','30','6');
       $title=array('序号','班级','班主任','节目名称','节目形式','节目串词','时长','排序');

     if(!is_array($list)){
      $list[]=array('',$year.'学年','暂无数据','','','');//没有数据设置无数据提示行防止溢出死机
     }else{
        $list=listAddID($list);//增加自动排序序号
     }
    $data[1]=array(
      'sheetname'=>$year.'学年',
      'header'=>$year.'学年 读书节活动节目汇总',
      'title'=>$title,
      'width'=>$width,
      'data'=>$list,
      );


    // dump($data);exit;
    $savefile=$year."学年读书节活动节目汇总".date(md);
    //输出文档函数在common/function.php中
    exportExcel($data,$savefile);

 } 
    public function upMusicfile(){
      
      $id=I('get.id');
      $this->my=D('JxDushujie')->find($id);
      $this->display();
    }
    public function doUploadFile() {
      $model=$this->dushujieModel;
     if(IS_POST){
       if(!$_FILES['upfile']['name']){
           $this->error("请选择上传文件后再提交");
        }
           /**去除一些非法字符**/
           $title=str_replace(array("，",","," ","　","•","/","?","<",">",".","*"),"",I('title'));//
           //dump($title);
           $savename=I('class').$title.date(md);//保存文件的命名规则 
           $config=C('DUSHUJIE_UPLOAD');
                  $config = array(
            'maxSize'    =>   100*1024*1024, // 设置附件上传大小
            'rootPath'   =>   './Uploads/',
            'savePath'   =>   'Dushujie/',
            'saveName'   =>   $savename,//iconv('utf-8', 'gbk', $savename),
            'exts'       =>    array('flv', 'mp4', 'zip', 'rar', 'mp3', 'wma'),
            'autoSub'    =>    true,
            'subName'    =>    array('date','Y'),
         );
           // dump($config);die;
         //$config['saveName'] =iconv('utf-8', 'gbk', $savename);
      
         $uploadfile = new \Think\Upload($config);//实例化上传类   
         $info   =  $uploadfile->upload();
         $file['ext']    =   pathinfo($_FILES['upfile']['name'], PATHINFO_EXTENSION);
            if(!$info) {// 上传错误提示错误信息
                $this->error($uploadfile->getError());
            }else{// 上传成功
          //保存表单数据
                $url= date('Y').'/'.$savename.'.'.$file['ext'];      
              $data=array( 
                         'id'=>I('id'),
                         "url" => $url,
                         "filename"=>$_FILES['upfile']['name'],                         
                         "uid" =>  is_login(),
                         "show_time"=>I('show_time'),
                             );
             
                 $data=$model->create($data); 
                 // dump($data);die;
                 $result=$model->save($data);
                 if(!result){
                 	$this->error($model->getError(),U('Jxgl/Dushujie/viewDushujie'));
                 }else{
                 	$this->success('上传成功！',U('Jxgl/Dushujie/viewDushujie'));
                 }
                
            }
         } 
     }
    //删除节目上报，仅管理员可删除
    public function deletedushujie(){
    	// define('IS_ROOT',   is_administrator());
    	if(is_administrator()){
    		$dushujieModel=$this->dushujieModel;
    		$id=I('id');
    		$result=$dushujie->delete($id);
	    	if($result !== false){               
			   $this->success('删除'.$result.'条记录', Cookie('__forward__'));                 
			    }else{
			     echo '删除失败！';
			    $this->error($dushujie->getError());
			    }  
	    	}else{
	        $this->error('对不起，权限不够，只有管理员才能删除！',U('Jxgl/Dushujie/viewDushujie'));
    	}
    }


}